package com.github.prontera.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.prontera.SpringUtils;
import com.github.prontera.domain.Tags;
import com.github.prontera.domain.enums.TagGroupTypeEnum;
import com.github.prontera.model.TreeUtll;

/**
 * 数据字典类
 */
public final class CommonTag {

	private volatile static Map<String, Tags> dicts = new HashMap<String, Tags>();

	private static Object lock = new Object();

	/**
	 * 获取动态选择列表
	 */
	public static Tags getFileds(TagGroupTypeEnum tagGroupTypeEnum) {
		if (tagGroupTypeEnum == null) {
			throw new IllegalArgumentException("参数错误！");
		}
		Tags tags = dicts.get(tagGroupTypeEnum.getDesc());
		synchronized (lock) {
			if (tags == null) {
				TagsService tagsService = SpringUtils.getBean(TagsService.class);
				Tags findSysDict = new Tags();
				findSysDict.setGroupType(tagGroupTypeEnum.getDesc());
				findSysDict.setStatus(0);
				findSysDict.setOrderBy("SYS_TAGS.group_type,SYS_TAGS.type");
				List<Tags> tagSource = tagsService.find(findSysDict);
				Tags parentTag = null;
				List<Tags> list = new ArrayList<Tags>();
				for (Tags tagsObj : tagSource) {
					if (tagsObj.getParentId() == null) {
						tags = parentTag = tagsObj;
					} else {
						list.add(tagsObj);
					}
				}
				if (parentTag != null) {
					parentTag.setChildren(list);
					;
				}
				dicts.put(parentTag.getGroupType(), parentTag);
			}
		}
		return tags;
	}

	/**
	 * 获取动态选择列表
	 */
	public static Tags getTreeFileds(TagGroupTypeEnum tagGroupTypeEnum,Long clientId) {
		if (tagGroupTypeEnum == null) {
			throw new IllegalArgumentException("参数错误！");
		}
		Tags tags = dicts.get(tagGroupTypeEnum.getDesc());
		synchronized (lock) {
			if (tags == null) {
				TagsService tagsService = SpringUtils.getBean(TagsService.class);
				Tags findSysDict = new Tags();
				findSysDict.setGroupType(tagGroupTypeEnum.getDesc());
				findSysDict.setClientId(clientId);
				findSysDict.setOrderBy("SYS_TAGS.group_type,SYS_TAGS.sort");
				List<Tags> tagSource = tagsService.findTag(findSysDict);
				List<Tags> nodeTags = TreeUtll.treeTags(tagSource);
				if (nodeTags != null) {
					Tags tagsNode = nodeTags.get(0);
					dicts.put(tagsNode.getGroupType(), tagsNode);
					return tagsNode;
				}
			}
			return tags;
		}
	}

}
